<?php

namespace app\admin\model\parts;

use think\Model;
use Throwable;
/**
 * Entry
 */
class Entry extends Model
{
    // 表名
    protected $name = 'parts_entry';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;


    public function partsInfo(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\parts\Info::class, 'parts_info_id', 'id');
    }
    public function manufacturerInfo(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\manufacturer\Info::class, 'partsInfo.manufacturer_info_id', 'id');
    }
    //配件入库逻辑
    public function PartsEntry($data):void
    {
        //切换数据表
        $this->model = new \app\admin\model\parts\Info;
        //更新相关数据
        $this->UpdataParts($data);

    }
    //配件入库
    public function UpdataParts($data):void
    {
        $this->model->startTrans();
        try {
            //更新配件库存
            $Row =$this->model->find($data['parts_info_id']);
            $Onur = $Row['parts_nur'];
            $NewNur = $Row['parts_nur'] + $data['entry_nur'];
            $Row['parts_nur'] = $NewNur;

            //更新配件建议零售价
            $Row['parts_money'] = $data['parts_money'];

            //更新配件成本
            $NewCost =  $this->LatestCost($data['parts_cost'],$data['entry_nur'],$Row['parts_cost'],$Onur);
            $Row['parts_cost'] = $NewCost;

            $res = $Row -> save($Row);
            $this->model->commit();

        } catch (Throwable $e) {
            $this->model->rollback();

        }
    }
    //最新配件成本
    public function LatestCost($Ncost,$Nnur,$Ocost,$Onur):float
    {
        return round(($Ocost * $Onur + $Ncost * $Nnur)/($Nnur + $Onur),2);
    }

}